/**
 * Copyright (C), 2015-2019, XXX有限公司
 * FileName: ServerHandler
 * Author:   kadibeieun
 * Date:     2019/8/12 17:02
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package clientLogin.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import clientLogin.protocol.Packet;
import clientLogin.protocol.PacketCodeC;
import clientLogin.protocol.request.LoginRequestPacket;
import clientLogin.protocol.response.LoginResponsePacket;

import java.util.Date;

/**
 * 〈一句话功能简述〉<br> 
 * 〈〉
 *
 * @author kadibeieun
 * @create 2019/8/12
 * @since 1.0.0
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {

    @Override

    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        System.out.println(new Date() + ": 客户端开始登录……");
        ByteBuf requestByteBuf = (ByteBuf) msg;
        Packet packet = PacketCodeC.INSTANCE.decode(requestByteBuf);

        if (packet instanceof LoginRequestPacket) {
            // 登录流程
            LoginRequestPacket loginRequestPacket = (LoginRequestPacket) packet;
            LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
            loginResponsePacket.setVersion(packet.getVersion());
            if (valid(loginRequestPacket)) {
                loginResponsePacket.setSuccess(true);
                System.out.println(new Date() + ": 登录成功!");
            } else {
                loginResponsePacket.setReason("账号密码校验失败");
                loginResponsePacket.setSuccess(false);
                System.out.println(new Date() + ": 登录失败!");
            }
            // 登录响应
            ByteBuf responseByteBuf = PacketCodeC.INSTANCE.encode(ctx.alloc(), loginResponsePacket);
            ctx.channel().writeAndFlush(responseByteBuf);
        }
    }



    private boolean valid(LoginRequestPacket loginRequestPacket) {
        boolean islogin = true;
        if (!loginRequestPacket.getUsername().equals("flash") || !loginRequestPacket.getPassword().equals("pwd")){
            islogin = false;
            return islogin;
        }
        return islogin;
    }

}